<?php
set_include_path(APP."Vendor/" . PATH_SEPARATOR . get_include_path());
App::import('Vendor', 'S3/S3');

class VideoController extends AppController {
    public $components = array('RequestHandler','Common');
    public $uses = array('File','Content','Category','Video','Option','Flavor','VideoFlavor','VideoThumbnail','VideoPromo','Keyword','ContentKeyword');
    public $helpers = array('Common');
    public $s3 = null;
    
    public function beforefilter(){
        $this->s3 = new S3(Configure::read('awsAccessKey'), Configure::read('awsSecretKey'));
    }
    
    public function beforerender(){
        //$this->Auth->allow('*'); 
        $this->set('subtitle','Control panel');
    }
    
    public function index() {
        
        $paginate = array();
        $condition = array();
        if($this->request->data){
            if($this->request->data['search']['title'] != ''){
                $condition['Content.title like'] = '%'.$this->request->data['search']['title'].'%';
            }
            
            if($this->request->data['search']['category'] != ''){
                $condition['Content.category'] = $this->request->data['search']['category'];
            }
            
            if($this->request->data['search']['startdate'] != '' && $this->request->data['search']['enddate'] != ''){
                $tsdate = $this->Common->mysqlDate($this->request->data['search']['startdate'],'dd/mm/yy','start');
                $tedate = $this->Common->mysqlDate($this->request->data['search']['enddate'],'dd/mm/yy','end');
                $condition['Content.created >='] = $tsdate;
                $condition['Content.created <='] = $tedate;
            }elseif($this->request->data['search']['startdate'] != ''){
                $tsdate = $this->Common->mysqlDate($this->request->data['search']['startdate'],'dd/mm/yy','start');
                $tedate = $this->Common->mysqlDate($this->request->data['search']['startdate'],'dd/mm/yy','end');
                $condition['Content.created >='] = $tsdate;
                $condition['Content.created <='] = $tedate;
            }elseif($this->request->data['search']['enddate'] != ''){
                $tsdate = $this->Common->mysqlDate($this->request->data['search']['enddate'],'dd/mm/yy','start');
                $tedate = $this->Common->mysqlDate($this->request->data['search']['enddate'],'dd/mm/yy','end');
                $condition['Content.created >='] = $tsdate;
                $condition['Content.created <='] = $tedate;
            }
        }
        
        $condition['Content.type'] = 'video';
        $paginate['conditions'] = $condition;
        $paginate['joins'] = array(array('table'=>'categories','type'=>'left','alias'=>'Category','conditions'=>array('Category.id = Content.category')));
        $paginate['fields'] = array('Content.*,Category.category');
        $paginate['limit'] = Configure::read('limit');
        
        $paginate['order'] = array('id' => 'desc');
        
        $this->paginate = $paginate;
        $data = $this->paginate('Content');
        $this->set('title','Video');
        $this->set('subtitle','Control panel');
        $this->set('data',$data);
        $this->set('category',$this->Category->find('list',array('fields'=>array('Category.id','Category.category'))));
    }
    
    public function videoopr($tab = 'basic') {
        
        if(isset($_GET['action'])){
            $opr = unserialize(base64_decode($_GET['action']));
            switch($opr['opr']){
                case 'thumbmail_set_as_default' :
                    $this->Session->setFlash(__('Default Thumbnail save successfully'),'success');
                    $this->VideoThumbnail->updateAll(array('VideoThumbnail.default_thumbnail'=>0),array('VideoThumbnail.content_id'=>$opr['content_id']));
                    $this->VideoThumbnail->updateAll(array('VideoThumbnail.default_thumbnail'=>1),array('VideoThumbnail.id'=>$opr['id']));
                    $this->redirect(array('controller' => 'video', 'action' => 'videoopr/thumbnail','?'=>$opr['queryString']));
                    exit;
                    break;
                case 'thumbmail_download' :
                    $tmp = $this->File->find('first',array('conditions'=>array('id'=>$opr['thumbnail_id'])));
                    if($tmp){
                        if(file_exists($tmp['File']['absolute_path'])){
                            header('Content-Type: application/octet-stream');
                            header('Content-Disposition: attachment; filename="'.basename($tmp['File']['absolute_path']).'"');
                            header('Content-Length: ' . filesize($tmp['File']['absolute_path']));
                            readfile($tmp['File']['absolute_path']);
                            exit;
                        }
                    }else{
                        $this->Session->setFlash('file not found','error');
                        $this->redirect(array('controller' => 'video', 'action' => 'videoopr/thumbnail','?'=>$opr['queryString']));
                    }
                    exit;
                    break;
                case 'thumbmail_delete' :
                    $tmp = $this->File->find('first',array('conditions'=>array('id'=>$opr['thumbnail_id'])));
                    if($tmp){
                        //Delete pyhsical file
                        if(file_exists($tmp['File']['absolute_path'])){
                            if(unlink($tmp['File']['absolute_path'])){
                                $this->Session->setFlash('Delete file successfully','info');    
                            }
                        }
                        
                        //Delete data in table
                        if($this->File->delete(array('id'=>$opr['thumbnail_id']))){
                            $this->Session->setFlash('Delete record from file table','info');
                        }
                        
                        //Delete record from video thumbnail table
                        if($this->VideoThumbnail->delete(array('VideoThumbnail.id'=>$opr['id']))){
                            $this->Session->setFlash('Video thumbnail record delete from video thumbnail table','info');
                        }
                    }
                    $this->redirect(array('controller' => 'video', 'action' => 'videoopr/thumbnail','?'=>$opr['queryString']));
                    break;
                case 'uploadthumbnail' :
                   $response = array();
                    $dir = 'uploads'.'/thumbs';
                    if($_FILES){
                        if ($_FILES["uploadthumbfile"]["error"] > 0) {
                            $response['error'] = $_FILES["uploadthumbfile"]["error"];
                        }else {
                            $ext = end((explode(".", $_FILES["uploadthumbfile"]["name"])));
                            $tmpName = uniqid().'.'.$ext;
                            $tmpFilename = $dir.'/'.$tmpName;
                            if(move_uploaded_file($_FILES["uploadthumbfile"]["tmp_name"],$tmpFilename)){
                                $response['success'][] = 'File save';
                                $absPath = WWW_ROOT.$tmpFilename;
                                $tmp = $this->Common->getFileInfo($absPath);
                                if(file_exists($tmp['filenamepath'])){
                                    $thumb['id'] = null;
                                    $thumb['name'] = $tmp['filename'];
                                    $thumb['type'] = 'thumbnail';
                                    $thumb['minetype'] = isset($tmp['mime_type']) ? $tmp['mime_type'] : '';
                                    $thumb['relative_path'] = 'uploads/thumbs/'.$tmp['filename'];
                                    $thumb['absolute_path'] = $tmp['filenamepath'];
                                    $thumb['status'] = 1;
                                    $thumb['uid'] = $this->Auth->user('id');
                                    $thumb['info'] = base64_encode(serialize($tmp));
                                    $thumb = $this->File->save($thumb);
                                    $response['success'][] = 'File data save in files table';
                                    
                                    //Save data in video thumbnail table
                                    if(isset($thumb['File']['id']) && $thumb['File']['id'] != ''){
                                        $tmpVideothumbnail = array();
                                        $tmpVideothumbnail['id'] = null;
                                        $tmpVideothumbnail['content_id'] = $this->request->data['content_id'];
                                        $tmpVideothumbnail['file_id'] = $thumb['File']['id'];
                                        $tmpVideothumbnail['default_thumbnail'] = '0';
                                        $tmpVideothumbnail['status'] = '1';
                                        $this->VideoThumbnail->save($tmpVideothumbnail);
                                    }
                                }
                            }
                        }
                    }
                    
                    if(array_key_exists('error',$response)){
                        echo 'false';
                    }else{
                        $this->Session->setFlash(__('Thumbnail upload successfully.'),'success');
                        echo 'true';
                    }
                    exit;
                    break;
                case 'setflavor_convert' :
                    $this->VideoFlavor->save(array('flavor_id'=>$opr['flavor_id'],'content_id'=>$opr['id'],'status'=>'inprocess'));
                    $this->Session->setFlash(__('Change successfully.'),'success');
                    $this->redirect(array('controller' => 'video', 'action' => 'videoopr/flavors','?'=>$opr['queryString']));
                    exit;
                    break;
                case 'setflavor_cancel' :
                    $tmp = $this->VideoFlavor->deleteAll(array('VideoFlavor.flavor_id'=>$opr['flavor_id'],'VideoFlavor.content_id'=>$opr['id'],'VideoFlavor.status'=>'inprocess'));
                    if($tmp){
                        $this->Session->setFlash(__('Change successfully.'),'success');
                    }else{
                        $this->Session->setFlash(__('error occor.'),'success');
                    }
                    $this->redirect(array('controller' => 'video', 'action' => 'videoopr/flavors','?'=>$opr['queryString']));
                    exit;
                    break;
                case 'setflavor_delete' :
                    
                    break;
                case 'delete' :
                    $tmp = $this->Content->deleteContent($opr['id']);
                    if($tmp){
                        $this->Session->setFlash(__('Video delete successfully.'),'success');
                        $this->redirect(array('controller' => 'video', 'action' => 'index'));
                    }else{
                        $this->Session->setFlash(__('Video not found.'),'error');
                        $this->redirect(array('controller' => 'video', 'action' => 'index'));
                    }
                    break;
                case 'edit' :
                        switch($tab){
                            case 'basic' :
                                if($this->request->data){
                                    if($this->Content->validates() == true){
                                        
                                        //Save keywords
                                        $this->saveKeywords($opr['id'],$this->request->data['contents']['keywords']);
                                        
                                        if($this->Content->save($this->request->data['contents'])){
                                            $this->Session->setFlash(__('Content Save Successfully.'),'success');
                                        }else{
                                            $this->Session->setFlash(__('Some error.'),'error');
                                        }
                                    }else{
                                        $errorStr = '<ul>';
                                        foreach($this->Content->validationErrors as $errors){
                                            foreach($errors as $error){
                                                $errorStr .= sprintf('<li>%s</li>',$error);    
                                            }
                                        }
                                        $errorStr .= '</ul>';
                                        $this->Session->setFlash(__($errorStr),'error');
                                    }
                                }
                                
                                $query = sprintf('select c.id,c.type,c.title,c.description,c.category,c.user_id,group_concat(k.name) as keywords,c.status from contents c
                                                    left join content_keywords ck on ck.content_id = c.id
                                                    left join keywords k on k.id = ck.keyword_id
                                                    where c.id = %d',$opr['id']);
                                
                                $tmp = reset($this->Content->query($query));
                                $this->request->data = array('contents'=>array_merge($tmp['c'],$tmp[0]));
                                $this->set('category',$this->Category->find('list',array('fields'=>array('Category.id','Category.category'))));
                                break;
                            case 'advanced' :
                                break;
                            case 'availability' :
                                break;
                            case 'promo' :
                                    $query = sprintf('SELECT f.* FROM `contents` c left join videos v on v.content_id = c.id left join files f on f.id = v.file_id where c.id = %d',$opr['id']);
                                    $tmp = reset($this->Content->query($query));
                                    if(file_exists($tmp['f']['absolute_path'])){
                                        $fileInfo = $this->Common->getFileInfo($tmp['f']['absolute_path']);
                                        $this->set('fileinfo',$fileInfo);
                                    }
                                    
                                    if($this->request->data){
                                        $response['result'] = 'false';
                                        $pdata = $this->request->data['videopromo'];
                                        $fileInfo = $this->Common->getPromoVideo($tmp['f']['absolute_path'],$pdata['start_time'],$pdata['end_time'] - $pdata['start_time']);
                                        if(file_exists($fileInfo['filenamepath'])){
                                            $tmpFileInfo = array();
                                            
                                            //Insert data in files table
                                            $tmpFileInfo['name'] = $fileInfo['filename'];
                                            $tmpFileInfo['type'] = 'promo_video';
                                            $tmpFileInfo['minetype'] = $fileInfo['mime_type'];
                                            $tmpFileInfo['relative_path'] = str_replace(WWW_ROOT,'',$fileInfo['filenamepath']);
                                            $tmpFileInfo['absolute_path'] = $fileInfo['filenamepath'];
                                            $tmpFileInfo['status'] = 1;
                                            $tmpFileInfo['uid'] = $this->Auth->user('id');
                                            $tmpFileInfo['info'] = base64_encode(serialize($fileInfo));
                                            if($tmpFileInfo = $this->File->save($tmpFileInfo)){
                                                
                                                //Get thumbnail from promo video
                                                $tmp = $this->Common->getVideoImage($fileInfo['filenamepath']);
                                                $thumb = array();
                                                if(file_exists($tmp['filenamepath']) && $tmp['filesize'] > 0){
                                                    $thumb['id'] = null;
                                                    $thumb['name'] = $tmp['filename'];
                                                    $thumb['type'] = 'promo_video_thumbnail';
                                                    $thumb['minetype'] = isset($tmp['mime_type']) ? $tmp['mime_type'] : '';
                                                    $thumb['relative_path'] = 'thumbs/'.$tmp['filename'];
                                                    $thumb['absolute_path'] = $tmp['filenamepath'];
                                                    $thumb['status'] = 1;
                                                    $thumb['uid'] = $this->Auth->user('id');
                                                    $thumb['info'] = base64_encode(serialize($tmp));
                                                    $thumb = $this->File->save($thumb);
                                                }
                                                
                                                
                                                if(isset($tmpFileInfo['File']['id'])){
                                                    $tmp = array();
                                                    $tmp['content_id'] = $opr['id'];
                                                    $tmp['file_id'] = $tmpFileInfo['File']['id'];
                                                    $tmp['thumb_id'] = isset($thumb['File']['id']) ? $thumb['File']['id'] : 0;
                                                    $tmp['default_thumbnail'] = 0;
                                                    $tmp['status'] = 1;
                                                    if($tmp = $this->VideoPromo->save($tmp)){
                                                        $this->Session->setFlash(__('Promo Video Save Successfully.'),'success');
                                                        $response['result'] = 'true';
                                                    }
                                                }
                                            }
                                        }
                                        echo json_encode($response);
                                        exit;
                                    }
                                    
                                    //Listing of thumbnails
                                    $query = sprintf('select * from video_promos vp
                                                     left join files video on video.id = vp.file_id
                                                     left join videos v on v.content_id = vp.content_id
                                                     left join files thumb on thumb.id = vp.thumb_id
                                                     where vp.content_id = %d order by vp.id desc',$opr['id']);
                                    $resultSet = $this->VideoPromo->query($query);
                                    $this->set('promo_video',$resultSet);
                                    
                                break;
                            case 'thumbnail' :
                                
                                if($this->request->data){
                                    if(isset($this->request->data['thumbnailcrop'])){
                                        
                                        $response['result'] = 'false';
                                        $data = $this->request->data['thumbnailcrop'];
                                        if($data['x'] > 0 && $data['y'] > 0 && $data['w'] > 0 && $data['h'] > 0){
                                            $tmp = $this->File->find('first',array('conditions'=>array('id'=>$data['file_id'])));
                                            if($tmp){
                                                if(file_exists($tmp['File']['absolute_path'])){
                                                    
                                                    $targ_w = $targ_h = 150;
                                                    $jpeg_quality = 90;
                                                    switch($tmp['File']['minetype']){
                                                        case 'image/png' :
                                                            $img_r = @imagecreatefrompng($tmp['File']['absolute_path']);
                                                            break;
                                                        case 'image/jpeg' :
                                                            $img_r = @imagecreatefromjpeg($tmp['File']['absolute_path']);
                                                            break;
                                                    }
                                                    
                                                    $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
                                                    imagecopyresampled($dst_r,$img_r,0,0,$data['x'],$data['y'],$targ_w,$targ_h,$data['w'],$data['h']);
                                                    
                                                    $tmpFilename = sprintf('%suploads/thumbs/%s.jpg',WWW_ROOT,uniqid());
                                                    imagejpeg($dst_r,$tmpFilename,$jpeg_quality);
                                                    if(file_exists($tmpFilename)){
                                                        $info = $this->Common->getFileInfo($tmpFilename);
                                                        $tmpFileInfo = array();
                                                        //Insert data in files table
                                                        $tmpFileInfo['name'] = $info['filename'];
                                                        $tmpFileInfo['type'] = 'thumbnail';
                                                        $tmpFileInfo['minetype'] = $info['mime_type'];
                                                        $tmpFileInfo['relative_path'] = str_replace(WWW_ROOT,'',$info['filenamepath']);
                                                        $tmpFileInfo['absolute_path'] = $info['filenamepath'];
                                                        $tmpFileInfo['status'] = 1;
                                                        $tmpFileInfo['uid'] = $this->Auth->user('id');
                                                        $tmpFileInfo['info'] = base64_encode(serialize($info));
                                                        if($tmpFileInfo = $this->File->save($tmpFileInfo)){
                                                            
                                                            //Insert data in video_thumbnail table
                                                            if(isset($tmpFileInfo['File']['id'])){
                                                                $tmp = array();
                                                                $tmp['content_id'] = $opr['id'];
                                                                $tmp['file_id'] = $tmpFileInfo['File']['id'];
                                                                $tmp['default_thumbnail'] = 0;
                                                                $tmp['status'] = 1;
                                                                if($tmp = $this->VideoThumbnail->save($tmp)){
                                                                    $this->Session->setFlash(__('Thumbnail Save Successfully.'),'success');
                                                                    $response['result'] = 'true';
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            echo json_encode($response);
                                            exit;
                                        }else{
                                            
                                        }
                                        
                                    }elseif(isset($this->request->data['thumbnailgrab'])){
                                        
                                        $response = array();
                                        $response['result'] = 'false';
                                        $data = $this->request->data['thumbnailgrab'];
                                        $duration = $data['seconds'];
                                        
                                        //Fetch data from content_id
                                        $query = sprintf('select * from contents c left join videos v on v.content_id = c.id left join files f on f.id = v.file_id where c.id = %d ',$opr['id']);
                                        $resultSet = $this->Content->query($query);
                                        $tmp = $resultSet['0']['f'];
                                        if(file_exists($tmp['absolute_path'])){
                                            $info = $this->Common->getVideoImage($tmp['absolute_path'],$duration);
                                            
                                            $tmpFileInfo = array();
                                            //Insert data in files table
                                            $tmpFileInfo['name'] = $info['filename'];
                                            $tmpFileInfo['type'] = 'thumbnail';
                                            $tmpFileInfo['minetype'] = $info['mime_type'];
                                            $tmpFileInfo['relative_path'] = str_replace(WWW_ROOT,'',$info['filenamepath']);
                                            $tmpFileInfo['absolute_path'] = $info['filenamepath'];
                                            $tmpFileInfo['status'] = 1;
                                            $tmpFileInfo['uid'] = $this->Auth->user('id');
                                            $tmpFileInfo['info'] = base64_encode(serialize($info));
                                            if($tmpFileInfo = $this->File->save($tmpFileInfo)){
                                                
                                                //Insert data in video_thumbnail table
                                                if(isset($tmpFileInfo['File']['id'])){
                                                    $tmp = array();
                                                    $tmp['content_id'] = $opr['id'];
                                                    $tmp['file_id'] = $tmpFileInfo['File']['id'];
                                                    $tmp['default_thumbnail'] = 0;
                                                    $tmp['status'] = 1;
                                                    if($tmp = $this->VideoThumbnail->save($tmp)){
                                                        $this->Session->setFlash(__('Thumbnail Save Successfully.'),'success');
                                                        $response['result'] = 'true';
                                                    }
                                                }
                                            }
                                        }
                                        echo json_encode($response);
                                        exit;
                                    }
                                }
                                
                                //Listing of thumbnails
                                $query = sprintf('select * from video_thumbnails vt left join files f on f.id = vt.file_id where vt.content_id = %d order by vt.id desc',$opr['id']);
                                $resultSet = $this->VideoThumbnail->query($query);
                                $this->set('thumbnails',$resultSet);
                                
                                //Get Default Image
                                $default_image = null;
                                foreach($resultSet as $key=>$val){
                                    if($val['vt']['default_thumbnail'] == 1){
                                        if(file_exists($val['f']['absolute_path'])){
                                            $default_image = $val['f'];
                                        }
                                    }
                                }
                                $this->set('default_image',$default_image);
                                break;
                            case 'flavors' :
                                $query = sprintf('select * from flavors f
                                                 left join (select id,flavor_id,file_id,status from video_flavors where content_id = %d) vf on vf.flavor_id = f.id
                                                ',$opr['id']);
                                $resultSet = $this->Content->query($query);
                                $this->set('flavorData',$resultSet);
                                break;
                        }
                        
                        $this->set('data',$this->Content->find('first',array('conditions'=>array('Content.id'=>$opr['id']))));
                        
                    break;
            }
        }
        
        $this->set('tab',$tab);
        $this->set('title','Video');
        $this->set('back',$this->referer());
    }
    
    public function saveKeywords($content_id,$keywords = null){
        if($keywords != null){
            $tmp = explode(',',$keywords);
            $keyword_ids = array();
            foreach($tmp as $key=>$val){
                $resultSet = $this->Keyword->find('first',array('conditions'=>array('name'=>$val)));
                if(!empty($resultSet)){
                    $keyword_ids[] = $resultSet['Keyword']['id'];
                }else{
                    if($this->Keyword->save(array('id'=>'null','name'=>$val,'status'=>1))){
                        $resultSet = $this->Keyword->find('first',array('conditions'=>array('name'=>$val)));
                        $keyword_ids[] = $resultSet['Keyword']['id'];
                    }
                }
            }
            
            //Delete all keyword of content
            if($this->ContentKeyword->deleteall(array('ContentKeyword.content_id' => $content_id))){
                foreach($keyword_ids as $key=>$val){
                    $this->ContentKeyword->save(array('id'=>null,'content_id'=>$content_id,'keyword_id'=>$val,'status'=>1));
                }    
            }
        }
    }
    
    public function detail() {
        
        if(isset($_GET['action'])){
            
            $data = array();
            $opr = unserialize(base64_decode($_GET['action']));
            switch($opr['opr']){
                case 'detail' :
                    $query = sprintf('Select * from contents 
                                        left join videos on videos.content_id = contents.id
                                        left join files vid on vid.id = videos.file_id 
                                        left join files thumb on thumb.id = videos.thumb_id 
                                        where contents.id = %d',$opr['id']);
                    $data = reset($this->Content->query($query));
                    $this->set('data',$data);
                    break;
            }
        }
        
        $this->set('title','Video');
        $this->set('subtitle','Control panel');
    }
    
    public function setting($tab = 'flavor') {
        $user = $this->Session->read("Auth.User");
        switch($tab){
            case 'flavor' :
                if($this->request->data){
                    $record = $this->Option->find('first',array('conditions'=>array('key'=>'flavor_settings','user_id'=>$user['id'])));
                    if(empty($record)){
                        $data = array('user_id'=>$user['id'],'key'=>'flavor_settings','value'=>serialize($this->request->data),'group'=>'flavor');
                        $this->Option->save($data);
                    }else{
                        if(isset($record['Option']['id'])){
                            $data = array('id'=>$record['Option']['id'],'user_id'=>$user['id'],'key'=>'flavor_settings','value'=>serialize($this->request->data),'group'=>'flavor');
                            $this->Option->save($data);
                        }
                    }
                    $this->Session->setFlash(__('Flavor saved successfully'),'success');
                }
                
                $records = $this->Flavor->find('all');
                $savedData = $this->Option->find('first',array('conditions'=>array('key'=>'flavor_settings','user_id'=>$user['id'])));
                if(!empty($savedData)){
                    if(isset($savedData['Option']['value'])){
                        $this->request->data = unserialize($savedData['Option']['value']);
                    }
                }
                
                $this->set('data',$records);
                break;
            case 'player' :
                
                if($this->request->data){
                    $record = $this->Option->find('first',array('conditions'=>array('key'=>'player_settings','user_id'=>$user['id'])));
                    if(empty($record)){
                        $data = array('user_id'=>$user['id'],'key'=>'player_settings','value'=>serialize($this->request->data),'group'=>'player');
                        $this->Option->save($data);
                    }else{
                        if(isset($record['Option']['id'])){
                            $data = array('id'=>$record['Option']['id'],'user_id'=>$user['id'],'key'=>'player_settings','value'=>serialize($this->request->data),'group'=>'player');
                            $this->Option->save($data);
                        }
                    }
                    $this->Session->setFlash(__('Player settings saved successfully'),'success');
                }
                
                $record = $this->Option->find('first',array('conditions'=>array('key'=>'player_settings','user_id'=>$user['id'])));
                if(!empty($record)){
                    if(isset($record['Option']['value'])){
                        $this->request->data = unserialize($record['Option']['value']);
                    }
                }
                
                
                //Player type
                $this->set('player_type',array('html5'=>'Html 5','flash'=>'Flash'));
                
                //Player skins
                $this->set('player_skin',array('beelden'=>'Beelden','bekle'=>'Bekle','five'=>'Five'
                                                ,'glow'=>'Glow','roundster'=>'Roundster','six'=>'Six'
                                                ,'stormtrooper'=>'Stormtrooper','vapor'=>'Vapor'));
                
                $this->set('font',array('Arial,Helvetica,sans-serif'=>'Arial',
                                        'Arial Black,Gadget,sans-serif'=>'Arial Black',
                                        'Comic Sans MS,cursive'=>'Comic Sans MS',
                                        'Courier New,Courier,monospace'=>'Courier New',
                                        'Georgia,serif'=>'Georgia',
                                        'Lucida Console,Monaco,monospace'=>'Lucida Console',
                                        'Tahoma,Geneva,sans-serif'=>'Tahoma',
                                        'Verdana,Geneva,sans-serif'=>'Verdana'));
                
                $this->set('aspect_ration',array('4:3'=>'4:3','16:9'=>'16:9','21:9'=>'21:9'));
                $this->set('logo_position',array('top-right'=>'Top Right','top-left'=>'Top Left','bottom-right'=>'Bottom Right','bottom-left'=>'Bottom Left'));
                $this->set('range',array_combine(range(1,100,1),range(1,100,1)));
                break;
        }
        
        $this->set('tab',$tab);
        $this->set('title','Video');
    }
    
    public function status() {
        
        $paginate = array();
        $paginate['conditions'] = null;
        $paginate['fields'] = array('Content.*,VideoFlavor.*,Flavor.*,Category.category');
        $paginate['joins'] = array(
                                   array('table'=>'contents','type'=>'left','alias'=>'Content','conditions'=>array('Content.id = VideoFlavor.content_id')),
                                   array('table'=>'categories','type'=>'left','alias'=>'Category','conditions'=>array('Category.id = Content.category')),
                                   array('table'=>'flavors','type'=>'left','alias'=>'Flavor','conditions'=>array('Flavor.id = VideoFlavor.flavor_id'))
                                );
        $paginate['order'] = array('VideoFlavor.id' => 'desc');
        $paginate['limit'] = Configure::read('limit');
        
        $this->paginate = $paginate;
        $data = $this->paginate('VideoFlavor');
        $this->set('data',$data);
        $this->set('title','Video');
    }
    
    public function renderJwPlayer($elementId,$contentId,$width=null,$height=null,$settings = null){
	
        $record = $this->Option->find('first',array('conditions'=>array('key'=>'player_settings')));
        
        $player = array();
        if(isset($record['Option']['id'])){
            $payerSettings = unserialize($record['Option']['value']);
            
            //General settings
            $player['mute'] = $payerSettings['player']['mute'];
            $player['repeat'] = $payerSettings['player']['repeat_video'];
            $player['skin'] = $payerSettings['player']['player_skin'];
            $player['androidhls'] = $payerSettings['player']['androidhls'];
            $player['controls'] = $payerSettings['player']['controls'];
            $player['autostart'] = $payerSettings['player']['auto_start'];
            $player['width'] = isset($width) ? $width : $payerSettings['player']['width'];
            $player['height'] = isset($height) ? $height : $payerSettings['player']['height'];
            $player['aspectratio'] = $payerSettings['player']['player_aspectration'];
            
            //Caption settings
            $player['captions']['color'] = $payerSettings['player']['caption_color'];
            $player['captions']['fontSize'] = $payerSettings['player']['caption_fontsize'];
            $player['captions']['fontfamily'] = $payerSettings['player']['caption_fontfamily'];
            $player['captions']['fontOpacity'] = $payerSettings['player']['caption_fontopacity'];
            $player['captions']['backgroundColor'] = $payerSettings['player']['caption_backgroundcolor'];
            $player['captions']['backgroundOpacity'] = $payerSettings['player']['caption_backgroundopacity'];
            $player['captions']['windowColor'] = $payerSettings['player']['caption_windowcolor'];
            $player['captions']['windowOpacity'] = $payerSettings['player']['caption_windowopacity'];
            
            //About Settings
            $player['abouttext'] = $payerSettings['player']['about_text'];
            $player['aboutlink'] = $payerSettings['player']['about_link'];
        }
        
        if($settings!=null){
            $settings = _decode($settings);
            foreach($settings as $key=>$val){
                $player[$key] = $val;   
            }
        }
        
        //Get content detail
        $query = sprintf('select * from contents c
                         left join videos v on v.content_id = c.id
                         left join files video on video.id = v.file_id
                         left join files thumb on thumb.id = v.file_id
                         where c.id = %d',$contentId);
        $tmp = reset($this->Content->query($query));
        
	$player['file'] = Router::url('/', true).$tmp['video']['relative_path'];
	$player['image'] = Router::url('/', true).$tmp['thumb']['relative_path'];
	echo sprintf('<script>jwplayer("%s").setup(%s);</script>',$elementId,json_encode($player));
    }
    
    
    public function preview() {
        $response = array();
        if(isset($_GET['action'])){
            $opr = unserialize(base64_decode($_GET['action']));
            switch($opr['opr']){
                case 'preview' :
                    $query = sprintf('Select vid.relative_path,thumb.relative_path from contents 
                                        left join videos on videos.content_id = contents.id
                                        left join files vid on vid.id = videos.file_id 
                                        left join files thumb on thumb.id = videos.thumb_id 
                                        where contents.id = %d',$opr['id']);
                    
                    $tmp = reset($this->Content->query($query));
                    if($tmp['vid']['relative_path'] != "" && $tmp['thumb']['relative_path'] != ""){
                        $response['response'] = 'true';
                        $response['data'] = $tmp;
                    }else{
                        $response['response'] = 'false';
                        $response['error'] = 'Video file not found';
                    }
                    break;
                default :
                    $response['response'] = 'false';
                    break;
            }
        }
        
        $this->layout = 'ajax';
        $this->RequestHandler->setContent('json', 'application/json');
        $this->set('data',json_encode($response));
    }
    
    
    public function upload() {
        $this->set('title','Video');
        $this->set('subtitle','Control panel');
    }
    
    public function bulkupload($tab = 'csv') {
        
        $response = array();
        $response['result'] = 'false';
        switch($tab){
            case 'ftp' :
                if($this->request->data){
                    $data = $this->request->data['ftp'];
                    if(!empty($data['username']) && !empty($data['password'])){
                        $conn_id = @ftp_connect($data['host']);
                        if($conn_id){
                            $response['message'][] = 'Successfully connect with server';
                            
                            //Try to login
                            if(@ftp_login ($conn_id, $data['username'],$data['password'])){
                                
                                $data['path'] = $data['path'] != '' ? $data['path'] : '/';
                                $rawfiles = ftp_rawlist($conn_id, $data['path']); //true being for recursive
                                $tmpData = array();
                                
                                if($data['path'] != '/') {
                                    $tmp = explode('/',substr($data['path'],0,-1));
                                    array_pop($tmp);
                                    $tmp = implode('/',$tmp).'/';
                                    $tmpData['dir'][] = array('name'=>'..','path'=>$tmp);
                                }
                                
                                foreach ($rawfiles as $rawfile){
                                    $info = preg_split("/[\s]+/", $rawfile, 9);
                                    if(substr($info[0],0,1) == 'd'){
                                        $tmp = $data['path'] == '/' ? '/'.$info[8].'/' : $data['path'].$info[8].'/';
                                        $tmpData['dir'][] =  array('name'=>$info[8],'path'=>$tmp);
                                    }else{
                                        $tmpData['file'][] = $info;
                                    }
                                }
                                $response['result'] = 'true';
                                $response['data'] = '<div class="table-responsive"><table class="table table-mailbox">';
                                $response['data'] .= '<tr class="unread">
                                            <th class="small-col">&nbsp;</th>
                                            <th class="small-col">Filename</th>
                                            <th class="small-col">FileSize</th>
                                            <th class="small-col">FileType</th>
                                            <th class="small-col">Last Modified</th>
                                            <th class="small-col">Permission</th></tr>';
                                
                                if(isset($tmpData['dir'])){
                                    foreach($tmpData['dir'] as $key=>$val){
                                        if(isset($val['path'])){
                                            $response['data'] .= '<tr class="unread">';
                                            $response['data'] .= '<td class="small-col"><i class="fa fa-fw fa-folder-o"></i></td>';
                                            $response['data'] .= '<td class="small-col"><a href="'.$val['path'].'" class="ftpdir">'.$val['name'].'</a></td>';
                                            $response['data'] .= '<td class="small-col">--</td>';
                                            $response['data'] .= '<td class="small-col">--</td>';
                                            $response['data'] .= '<td class="small-col">--</td>';
                                            $response['data'] .= '<td class="small-col">--</td>';
                                            $response['data'] .= '</tr>';
                                        }
                                    }
                                }
                                
                                $validExt = array('mp4','avi','swf');
                                if(isset($tmpData['file'])){
                                    foreach($tmpData['file'] as $key=>$val){
                                        
                                        $fileext = end(explode('.',$val[8]));
                                        if(in_array($fileext,$validExt)){
                                            $size = _byteFormat(intval(trim($val[4])));
                                            $modified = date('d/m/Y',strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]));
                                            
                                            $response['data'] .= '<tr class="unread">';
                                            $response['data'] .= '<td class="small-col"><input class="ftpcheckbox" name="files[]" type="checkbox" value="'.$data['path'].$val[8].'" filesize="'.$size.'" filetype="'.$fileext.'" /></td>';
                                            $response['data'] .= '<td class="small-col filename">'.$val[8].'</td>';
                                            $response['data'] .= '<td class="small-col filesize">'.$size.'</td>';
                                            $response['data'] .= '<td class="small-col filetype">'.$fileext.'</td>';
                                            $response['data'] .= '<td class="small-col">'.$modified.'</td>';
                                            $response['data'] .= '<td class="small-col">'.$val[0].'</td>';
                                            $response['data'] .= '</tr>';    
                                        }
                                    }
                                }
                                $response['data'] .= '</table></div>';
                                
                            }else{
                                $response['result'] = 'false';
                                $response['message'][] = ' Username and password is wrong';
                            }
                            
                        }else{
                            $response['result'] = 'false';
                            $response['message'][] = ' Could not connect with server';
                        }
                    }else{
                        $response['result'] = 'false';
                        $response['message'][] = ' All fields are required';
                    }
                    echo json_encode($response);
                    exit;
                }
                break;
        }
        
        $this->set('title','Video');
        $this->set('tab',$tab);
    }
    
    public function ajaxupload($dir = null) {
        
        $response = array();
        //check directory
        if(!is_dir($dir)){
            if(mkdir($dir,777,true)){
                $response['success'] = 'Directory found';
            }else{
                $response['error'] = 'Directory not found';
            }
        }
        
        if($_FILES){
            if ($_FILES["file"]["error"] > 0) {
                $response['error'] = $_FILES["file"]["error"];
            } else {
                $ext = end((explode(".", $_FILES["file"]["name"])));
                $tmpName = uniqid().'.'.$ext;
                $tmpFilename = $dir.'/'.$tmpName;
                if(move_uploaded_file($_FILES["file"]["tmp_name"],$tmpFilename)){
                    
                    $response['success'][] = 'File save';
                    
                    $video = $videoTable = $thumb = $content = array();
                    $absPath = WWW_ROOT.$tmpFilename;
                    
                    //Save video to files tables
                    $video['name'] = $tmpName;
                    $video['type'] = 'video';
                    $video['minetype'] = $_FILES["file"]['type'];
                    $video['relative_path'] = $tmpFilename;
                    $video['absolute_path'] = $absPath;
                    $video['status'] = 1;
                    $video['uid'] = $this->Auth->user('id');
                    $video['info'] = base64_encode(serialize($this->Common->getFileInfo($absPath)));
                    if($video = $this->File->save($video)){
                        
                        $response['success'][] = 'File save in DB';
                        
                        //Get Image from video
                        $tmp = $this->Common->getVideoImage($absPath);
                        if(file_exists($tmp['filenamepath']) && $tmp['filesize'] > 0){
                            $thumb['id'] = null;
                            $thumb['name'] = $tmp['filename'];
                            $thumb['type'] = 'thumbnail';
                            $thumb['minetype'] = isset($tmp['mime_type']) ? $tmp['mime_type'] : '';
                            $thumb['relative_path'] = 'thumbs/'.$tmp['filename'];
                            $thumb['absolute_path'] = $tmp['filenamepath'];
                            $thumb['status'] = 1;
                            $thumb['uid'] = $this->Auth->user('id');
                            $thumb['info'] = base64_encode(serialize($tmp));
                            $thumb = $this->File->save($thumb);
                            $response['success'][] = 'Getting Image sucessfully'; 
                        }
                        
                        //Insert data in content table
                        $content['title'] = $_FILES["file"]["name"];
                        $content['type'] = 'video';
                        $content['status'] = 1;
                        $content['uid'] = $this->Auth->user('id');
                        if($content = $this->Content->save($content)){
                            
                            //Insert in Video table
                            $videoTable['content_id'] = $content['Content']['id'];
                            $videoTable['file_id'] = isset($video['File']['id']) ? $video['File']['id'] : null;
                            $videoTable['thumb_id'] = isset($thumb['File']['id']) ? $thumb['File']['id'] : null;
                            $videoTable['status'] = 1;
                            if($videoTable = $this->Video->save($videoTable)){
                                
                            }
                        }
                        
                        $this->Session->setFlash(__('File upload successfully.'),'success');
                        $response['success']['result'] = 'true';
                        $response['success']['redirect'] = Router::url('/', true).'video/videoopr?action='._encode(array('id'=>$content['Content']['id'],'opr'=>'edit'));
                    }
                }else{
                    $response['error'] = 'Error in uploading';
                }
                
            }
        }else{
            $response['error'] = 'Please check server settings';
        }
        
        $this->layout = 'ajax';
        $this->RequestHandler->setContent('json', 'application/json');
        $this->set('data',json_encode($response));
    }
}